<script type="text/javascript">
Ext.onReady(function(){
	Ext.QuickTips.init();

		var proxy = new Ext.data.HttpProxy({
			url: "<?php echo $this->baseUrl() . "despesas/index/?format=json";?> ",
			method: 'POST'
		});

		var recordFields = [
			{name: 'id', mapping: 'id'},
			{name: 'descricao', mapping: 'descricao'},
			{name: 'valor', mapping: 'valor'},
			{name: 'data', mapping: 'data'},
			{name: 'contas_id', mapping: 'contas_id'}
		];

		var despesasStore = new Ext.data.JsonStore({
			proxy: proxy,
			storeId: 'despesasStore',
			root: 'despesas',
			autoLoad: true,
			totalProperty: 'totalRows',
			remoteSort: true,
			fields: recordFields,
			idProperty: 'id'
		});

		var columnModel = [
			{
				header: 'Descrição',
				dataIndex: 'descricao',
				sortable: true
			}, {
				header: 'Valor',
				dataIndex: 'valor',
				sortable: true
			}, {
				header: 'Data',
				dataIndex: 'data',
				sortable: true
			}, {
				header: 'Conta afetada',
				dataIndex: 'contas_id',
				sortable: true
			}
		];

		var pagingToolbar = {
			xtype: 'paging',
			store: despesasStore,
			pageSize: 50,
			displayInfo: true
		};

		var grid = {
			xtype: 'editorgrid',
			columns: columnModel,
			id: 'despesasEditor',
			store: despesasStore,
			loadMask: true,
			bbar: pagingToolbar,
			stripeRows: true
		}

		var win = new Ext.Window({
			width: 500,
			height: 300,
			border: false,
			layout: 'fit',
			items: grid
		});

		var onConfirmDelete = Ext.emptyFn;
		var onDelete = Ext.emptyFn;
		var onCompleteEdit = function(treeEditor, newValue, oldValue) {
			if(newValue != oldValue){
	        	var treePanel =  Ext.getCmp('myTreePanel')
	        	treePanel.el.mask('Saving...', 'x-mask-loading');
		 
	        	var editNode = treeEditor.editNode;
	        	var editNodeId = editNode.id;
	        	Ext.Ajax.request({
		            url    : "<?php echo $this->baseUrl() . "categorias-despesas/edit/";?> ",
	            	method: 'post',
	            	params : {
		                id      : editNodeId,
	                	newName : newValue
	            	},
	            	success : function (response, opts) {
		                treePanel.el.unmask();
	                	var responseJson = Ext.decode(response.responseText);
	                	if (responseJson.success !== true) {
		                    editNode.setText(oldValue);
	                    	Ext.Msg.alert('Um erro ocorreu com o servidor. Tente novamente mais tarde.');
	                	}
	            	},
	            	failure : function (response, opts) {
		                treePanel.el.unmask();
	                	editNode.setText(oldValue);
	                	Ext.Msg.alert('Um erro ocorreu com o servidor. Tente novamente mais tarde.');
	            	}
	        	});
			}
	    }
		
		var onEdit = function(){
			var treePanel = Ext.getCmp('myTreePanel');
			var selectedNode = treePanel.getSelectionModel().getSelectedNode();

			if(!this.treeEditor){
				this.treeEditor = new Ext.tree.TreeEditor(treePanel, {}, {
					cancelOnEsc: true,
					completeOnEnter: true,
					selectOnFocus: true,
					allowBlank: false,
					listeners: {
						complete: onCompleteEdit
					}
				});
			}

			this.treeEditor.editNode = selectedNode;
			this.treeEditor.startEdit(selectedNode.ui.textNode);
		};
		var onCompleteAdd = Ext.emptyFn;
		var onAddNode = Ext.emptyFn;

		var buildCtxMenu = function(){
			return new Ext.menu.Menu({
				items:[{
					itemId: 'add',
					text: 'Adicionar categoria',
					handler: onAddNode
				}, {
					itemId: 'edit',
					text: 'Editar categoria',
					handler: onEdit
				}, {
					itemId: 'delete',
					handler: onDelete,
					text: 'Excluir categoria'
				}]
			})
		};

		var onCtxMenu = function(node, event){
			node.select();
			event.stopEvent();
			if(!this.ctxMenu){
				this.ctxMenu = buildCtxMenu();
			}

			var ctxMenu = this.ctxMenu;
			var addItem = ctxMenu.getComponent('add');
			var editItem = ctxMenu.getComponent('edit');
			var deleteItem = ctxMenu.getComponent('delete');

			ctxMenu.showAt(event.getXY());
		};
		
	var treeLoaderCategoriasDespesas = new Ext.tree.TreeLoader({
		url: '<?php echo $this->baseUrl() . "categorias-despesas/";?>'
	});

	var rootNodeCategoriasDespesas = new Ext.tree.AsyncTreeNode({
		text: 'Raíz'
	});
	
	var treeCategoriasDespesas = new Ext.tree.TreePanel({
		id: 'myTreePanel',
		loader: treeLoaderCategoriasDespesas,
		root: rootNodeCategoriasDespesas,
		rootVisible: false,
		animate: true,
		autoScroll: true,
		listeners: {
			click: function(n){
				if(n.attributes.leaf){
					var titulo = n.text;
					var novaAba = Ext.getCmp('myTabPanel').items.find(function(aba){
						return aba.title === titulo;
					});

					if(!novaAba){
						novaAba = Ext.getCmp('myTabPanel').add({
							title: titulo,
							html: 'aqui tenho que renderizar o grid de ' + titulo,
							tabTip: n.attributes.text,
							closable: true
						});
					}
					Ext.getCmp('myTabPanel').activate(novaAba);
				}	
			},
			contextmenu: onCtxMenu
		}
	});

	var despesasMenu = new Ext.Panel({
		title: 'Despesas',
		items: [treeCategoriasDespesas],
		border: false,
	});

	var receitasMenu = {
		title: 'Receitas',
		html: 'Aqui irão os meus ganhos'
	};

	var graficosMenu = {
		title: 'Gráficos',
		html: 'Bolar maneira de gerar gráficos para o usuário'
	};

	var infoTab = {
		title: 'Informação',
		id: 'infoTab',
		html: 'aqui eu irei colocar as informações de como usar o programa...',
		closable: false
	};

	var tabPanel = new Ext.TabPanel({
		activeTab: 0,
		id: 'myTabPanel',
		enableTabScroll: true,
		items: [infoTab],
		enableScroll: true
	});

	var viewport = new Ext.Viewport({
		layout: 'border',
		defaults: {
			bodyStyle: 'padding: 5px;'
		},

		items: [{
			region: 'north',
			html: 'Pensar em colocar menus, informações pro usuário e links',
			frame: true,
			height: 100
		}, {
			region: 'west',
			frame: true,
			layout: 'accordion',
			split: true,
			border: false,
			layoutConfig: {
				animate: true
			},
			items: [despesasMenu, receitasMenu, graficosMenu],
			width: 150
		}, {
			region: 'center',
			items: [tabPanel]
		}]
	});
})
</script>
